package cn.wit.test;


import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;

import javafx.application.Application;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyCode;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class DemoJavaFx extends Application{

	private Socket socket;
	
	private DataOutputStream dos;
	
	@Override
	public void start(Stage primaryStage) throws Exception {
		// TODO Auto-generated method stub
		
		VBox box = new VBox();
		
		box.setPadding(new Insets(10));
		
		//多行输入框
		TextArea ta = new TextArea();
		
		//把场景里面多得空间给多行输入框
		VBox.setVgrow(ta, Priority.ALWAYS);
		
		//单行输入框
		TextField tf = new TextField();
		
		//加到容器里面
		box.getChildren().addAll(ta,tf);
		
		//监听回车事件
		tf.setOnKeyPressed((event)->{
			
			KeyCode code = event.getCode();
			
			if(code == KeyCode.ENTER) {
				
				//获取输入框里面得内容
				String message = tf.getText();
	
				//如果为空，就不做任何事情
				if("".equals(message)) {
					return;
				}
				
				//把内容加到多行输入框,往后加
				ta.appendText(message+"\n");
				
				//刷新下面得输入框
				tf.setText("");
				
				//客户端结束处理
				if("88".equals(message)) {
					
					//关闭资源
					Utils.closeQuietly(dos);
					Utils.closeQuietly(socket);
					
					System.exit(0);//退出程序
					
				}
				
				try {
					dos.writeUTF(message);
					dos.flush();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			
		});
	
		
		//创建一个场景
		Scene scene = new Scene(box,400,300);
		
		primaryStage.setScene(scene);
		
		primaryStage.show();
		
		//打开socket
		openSocket();
		
	}
	
	private void openSocket() {
		// TODO Auto-generated method stub
		
		try {
			socket = new Socket("127.0.0.1",6666);
			dos = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream()));
			System.out.println("服务器已经连接上了。。。");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

	//关闭
	@Override
	public void stop() throws Exception {
		// TODO Auto-generated method stub
		super.stop();
		
		//关闭资源
		Utils.closeQuietly(dos);
		Utils.closeQuietly(socket);
	}
	
	public static void main(String[] args) {
		launch(args);
	}

}
